package com.ultrapower.ctool.xn_app;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.utils.SerializableMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class XunChaResultInfoActivity extends BaseActivity implements View.OnClickListener {
    private EditText bh_info_xc_result;
    private EditText xcbh_info_xc_result;
    private EditText xcname_info_xc_result;
    private EditText xcresult_info_xc_result;
    private TextView change_info_xc_result;
    private TextView delete_info_xc_result;
    private TextView back_info_xc_result;
    private CustomApplication application;
    private ProgressDialog progressDialog;
    private String identification;
    private String mId;
    //private OkHttpClient client = new OkHttpClient();
    private SerializableMap menu = new SerializableMap();
    private Gson gson = new Gson();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Map<String, String>> resultMap = new HashMap<String, Map<String, String>>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "操作成功", Toast.LENGTH_SHORT).show();
                    //Intent intent = new Intent(WangGeEvaluateInfoActivity.this, WangGeHandleActivity.class);
                    //startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "操作失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xun_cha_result_info);
        init();
        initData();
    }

    protected void init() {
        application = (CustomApplication) getApplication();
        Intent intent = getIntent();
        mId = intent.getStringExtra("remId");
        identification = intent.getStringExtra("identification");

        bh_info_xc_result = (EditText) findViewById(R.id.bh_info_xc_result);
        textMap.put("mid", bh_info_xc_result);

        xcbh_info_xc_result = (EditText) findViewById(R.id.xcbh_info_xc_result);
        textMap.put("cid", xcbh_info_xc_result);

        xcname_info_xc_result = (EditText) findViewById(R.id.xcname_info_xc_result);
        textMap.put("mname", xcname_info_xc_result);

        xcresult_info_xc_result = (EditText) findViewById(R.id.xcresult_info_xc_result);
        textMap.put("itemvalue", xcresult_info_xc_result);

        change_info_xc_result = (TextView) findViewById(R.id.change_info_xc_result);
        delete_info_xc_result = (TextView) findViewById(R.id.delete_info_xc_result);
        back_info_xc_result = (TextView) findViewById(R.id.back_info_xc_result);
        change_info_xc_result.setOnClickListener(this);
        delete_info_xc_result.setOnClickListener(this);
        back_info_xc_result.setOnClickListener(this);
    }

    public void initData() {
        showProgressDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "inspect/xcxmDetail/c_aj_xcxm-" + mId).post(requestBody).build();
                    response = client.newCall(request).execute();

                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        System.out.println("result:" + result);
                        resultMap = gson.fromJson(result, Map.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (Map.Entry<String, String> entry : resultMap.get("result").entrySet()) {
                                    System.out.println(entry.getKey() + "---------" + entry.getValue());
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().contains("\\.") ? entry.getValue().split("\\.")[0] : entry.getValue());
                                    }
                                }
                            }
                        });
                    } else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                } finally {
                    if (response != null) response.close();
                    closeProgressDialog();

                }
            }
        }).start();
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(XunChaResultInfoActivity.this);
            progressDialog.setMessage("正在加载，请稍等...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.change_info_xc_result:

                if ((identification != null && "rcxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目修改"))
                        || (identification != null && "zxxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目修改"))
                        ) {
                    Intent intent = new Intent(XunChaResultInfoActivity.this, ChangeXunChaResultActivity.class);
                    intent.putExtra("mid", String.valueOf(resultMap.get("result").get("mid")));
                    startActivity(intent);
                   // finish();
                } else {
                    Toast.makeText(getApplication(), "没有相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.delete_info_xc_result:
                if ((identification != null && "rcxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目删除"))
                        || (identification != null && "zxxc".equals(identification) && ((List) (application.getSerializableMap().getMap().get("m_aj_rcxc"))).contains("安监巡查项目删除"))
                        ) {
                    showProgressDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                FormBody.Builder builder = new FormBody.Builder();
                                List list = new ArrayList();
                                list.add(resultMap.get("result"));
                                builder.add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                builder.add("rows", gson.toJson(list));
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "grid/delete/c_aj_xcxm").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    Map<String, Object> suMap = gson.fromJson(result, Map.class);
                                    System.out.println(suMap);
                                    if ((boolean) suMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                        finish();
                                    } else {
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                }
                                closeProgressDialog();
                            } catch (Exception e) {
                                closeProgressDialog();
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();
                            }
                        }
                    }
                    ).start();
                } else {
                    Toast.makeText(getApplication(), "没有相关权限", Toast.LENGTH_SHORT).show();

                }
                break;
            case R.id.back_info_xc_result:
                finish();
                break;
        }
    }
}
